/*
 * 异步加载js
 * 使用方法 1、引入文件 2、loadJquery = new SyncLoad({gloabalName: 'jQuery', url: 'http://code.jquery.com/jquery-2.1.1.min.js'});
 */

export default class lazyLoader {
    constructor (config) {
        this._config = Object.assign({}, config);
        this._document = document;
        this._window = window;
        this._scriptLoaded = false;
    }

    load () {
        if (this._config.globalName && this._window[this._config.globalName]) {
            return Promise.resolve();
        }

        if (this._scriptLoadingPromise) return this._scriptLoadingPromise;
        const script = this._document.createElement('script');
        script.type = 'text/javascript';
        script.async = true;
        script.defer = true;
        script.src = this._config.url;

        this._scriptLoadingPromise = new Promise((resolve, reject) => {
            script.onload = (res) => {
                return resolve(res);
            };
            script.onerror = error => reject(error);
        });
        this._document.head.appendChild(script);
        return this._scriptLoadingPromise;
    }

}
